package jsyf.oa.service.wechat.service_company;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import jsyf.oa.dao.system.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.wechat.service_company.TokenEntity;
import jsyf.oa.facade.wechat.config.WeChatConst;
import jsyf.oa.facade.wechat.service_company.TokenFacade;

@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class TokenService implements TokenFacade {

    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private UserDao userDao;
    @Value("${wechat.serviceAccount.appId}")
    private String appId;

    @Value("${wechat.serviceAccount.appSecret}")
    private String appSecret;

    public String save(String jsonData, int type) {
        return tokenDao.save(jsonData, type);
    }

    @Override
    public JSONObject getToken() {
        return tokenDao.getToken();
    }

    @Override
    public JSONObject getContactsToken() {
        return tokenDao.getContactsToken();
    }

    @Override
    public String getServiceAccessToken(int type) {
        List<JSONObject> list = tokenDao.getTokenByType(type);
        String token = "";
        if (list != null && list.size() > 0) {
            //判断是否超2小时（提前200秒存储）
            TokenEntity entity = (TokenEntity) tokenDao.convertJson2Entity(list.get(0));
            if (Math.floor((tokenDao.getCurrentTime().getTime() - entity.getCreateTime().getTime()) / 1000) > entity.getExpiresIn() - 200 ) {
                token = getServiceAccessTokenByApi().getString("accessToken");
                return token;
            } else {
                token = list.get(0).getString("accessToken");
                return token;
            }
        } else {
            //token不存在
            token = getServiceAccessTokenByApi().getString("accessToken");
            return token;
        }
    }

    /**
     * 获取全部员工id,用来发送指定消息判断使用
     *
     * @return
     */
    @Override
    public JSONObject getAllStaff() {
        return tokenDao.getAllStaff();
    }

    @Override
    public JSONObject updateStaff(String jsonData) {
        return tokenDao.updateStaff(jsonData);
    }

    /**
     * 发送文字消息
     * userIds 多个以丨杠隔开
     * <p>1001|1002</p>
     *
     * @return
     */
    @Override
    public JSONObject sendTextMsg(String jsonData) {
        return tokenDao.sendTextMsg(jsonData);
    }

    /**
     * 员工入职
     * <p>
     * 注意:每个部门下的部门、成员总数不能超过3万个
     *
     * @return
     */
    @Override
    public JSONObject entry(String jsonString) {
        return tokenDao.entry(jsonString);
    }

    /**
     * 员工离职
     *
     * @return
     */
    @Override
    public JSONObject leave(String userId) {
       return tokenDao.leave(userId);
    }


    /**
     * 接口获取服务号token
     * @return
     */
    public JSONObject getServiceAccessTokenByApi() {

        TokenEntity accessToken = null;
        String requestUrl = WeChatConst.access_token_url.replace("APPID", appId).replace("APPSECRET", appSecret);
        JSONObject jsonObject = HttpUtil.request(requestUrl, "GET", null);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new TokenEntity();
                accessToken.setAccessToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInteger("expires_in"));
                accessToken.setCompanyId("201712161613432EAF27DBCCB7D0E6CA");
                //保存到数据库
                accessToken.setType(0);
                save(JSON.toJSONString(accessToken), 0);
            } catch (JSONException e) {
                accessToken = null;
            }
        }
        return (JSONObject) JSON.toJSON(accessToken);
    }

    @Override
    public void SignRemind(StringBuilder sb) {
        tokenDao.SignRemind(sb);
    }
}